/**
 * @Title: ItemController
 * @Package cn.com.yiqi.wsc.portal.controller.item
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-胥钰淋
 * @date 2017/2/22 9:53
 * @version V1.0
 */
package cn.com.yiqi.wsc.portal.controller.item;

import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultStatusEnum;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.dao.item.criteria.ItemCheckCriteria;
import cn.com.yiqi.wsc.dao.item.criteria.ItemCriteria;
import cn.com.yiqi.wsc.entity.item.ItemCheck;
import cn.com.yiqi.wsc.entity.item.ItemDTO;
import cn.com.yiqi.wsc.entity.user.User;
import cn.com.yiqi.wsc.enumeration.CheckResultEnum;
import cn.com.yiqi.wsc.enumeration.ItemPayType;
import cn.com.yiqi.wsc.enumeration.ItemStatusEnum;
import cn.com.yiqi.wsc.enumeration.UserType;
import cn.com.yiqi.wsc.portal.controller.BaseController;
import cn.com.yiqi.wsc.service.item.PortalItemService;
import cn.com.yiqi.wsc.service.item.enumerate.ItemKindEnum;
import cn.com.yiqi.wsc.service.outputExcel.OutPutService;
import cn.com.yiqi.wsc.service.user.UserService;
import cn.com.yiqi.wsc.util.JsonUtil;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 会员系统组-胥钰淋
 * @ClassName: ItemController
 * @Description: TODO
 * @date 2017/2/22 9:53
 */
@Controller
@RequestMapping("/item")
public class ItemController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private PortalItemService portalItemService;
    @Autowired
    private OutPutService outPutService;

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView("item/index");
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/add")
    public ModelAndView add() {
        ModelAndView mv = new ModelAndView("item/add");
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/outPut")
    public void outPut(@RequestBody ItemCriteria criteria, HttpServletRequest request, HttpServletResponse response) {
        List<ItemDTO> list = portalItemService.outPutItemList(criteria);
        String title = "商品列表";

        String[] hearders = new String[]{"商品名称", "商家", "类别", "是否积分商品", "状态", "销量", "库存", "创建时间", "创建人"};//表头数组
        String[] fields = new String[]{"name", "orgName", "typeName", "kindName", "statusName", "soldCount", "stock", "insertTime", "realName"};//People对象属性数组
        String creater = userService.getCurrentUser().getRealName();

        try {
            outPutService.outPutExcel(list, title, hearders, fields, creater, request, response);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    @RequestMapping("/edit")
    public ModelAndView edit(@RequestParam("itemId") Integer itemId, @RequestParam("kind") Integer kind) {
        ModelAndView mv;
        if (kind != 3) { // 非积分商品
            mv = new ModelAndView("item/detail");
        } else { // 积分商品
            mv = new ModelAndView("item/addPoints");
        }
        ItemCriteria criteria = new ItemCriteria();
        criteria.setItemId(itemId);

        mv.addObject("detail", JsonUtil.toJSON(portalItemService.detail(criteria).getData().get("detail")));
        mv.addObject("readonly", "false");
        this.getUserData(mv);

        return mv;
    }

    @RequestMapping("/addPoints")
    public ModelAndView addPoints() {
        ModelAndView mv = new ModelAndView("item/addPoints");
        mv.addObject("detail", "false");
        mv.addObject("readonly", "false");
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/review")
    public ModelAndView review() {
        ModelAndView mv = new ModelAndView("item/review");
        this.getUserData(mv);
        return mv;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Result list(@RequestBody ItemCriteria itemCriteria) {
        Result result = new Result();


        Integer kind = itemCriteria.getKind();
        if (kind != null) {
            if (kind == 1) {
                //是积分商品
                itemCriteria.setKind(3);
            }
            if (kind == 0) {
                //是不是积分商品
                itemCriteria.setKind(2);
            }

        }

        User user = userService.getCurrentUser();
        if (UserType.seller.getValue() == user.getType()) {
            itemCriteria.setOrgId(user.getOrgId());
        }
        result = portalItemService.pageList(itemCriteria);

        return result;
    }

    @RequestMapping("/vip/index")
    public ModelAndView vipIndex() {
        ModelAndView mv = new ModelAndView("vip/index");
        this.getUserData(mv);
        return mv;
    }


    @RequestMapping("/vip/list")
    @ResponseBody
    public Result pageListVip(@RequestBody ItemCriteria itemCriteria) {
        Result result = new Result();

        itemCriteria.setKind(ItemKindEnum.vip.getValue());
        result = portalItemService.pageList(itemCriteria);

        return result;

    }


    @RequestMapping("/insert")
    @ResponseBody
    public Result insert(@RequestBody ItemDTO itemDTO) {
        Result result = new Result();

        itemDTO.setKind(ItemKindEnum.item.getValue());
        //校验
        Result validateResult = validation(itemDTO);

        if (!ResultUtil.isSuccess(validateResult)) {
            //校验失败
            return validateResult;
        }

        User currentUser = userService.getCurrentUser();
        itemDTO.setOrgId(currentUser.getOrgId());
        itemDTO.setStatus(ItemStatusEnum.待提交.getValue());
        result = portalItemService.insert(itemDTO, currentUser.getId());

        return result;
    }


    private Result validation(ItemDTO itemDTO) {
        Result result = new Result();

/*
        if (itemDTO.getKind() == null) {
            return ResultUtil.paramError(result, "请选择类型");
        }
*/

        if (itemDTO.getKind() == ItemKindEnum.item.getValue()) {
            if (itemDTO.getTypeId() == null) {
                return ResultUtil.paramError(result, "请选择类目");
            }
            if (StringUtils.isEmpty(itemDTO.getDesc())) {
                return ResultUtil.paramError(result, "请填写商品描述");
            }

            if (!portalItemService.isServiceItem(itemDTO.getTypeId())) {
                //是不是服务商品，不是服务商品才需要填写原价
                if (itemDTO.getInitialPrice() == null) {
                    return ResultUtil.paramError(result, "请填写原价");
                }
            }

            if (itemDTO.getSalePrice() == null) {
                return ResultUtil.paramError(result, "请填写现价");
            }
        }

        if (StringUtils.isEmpty(itemDTO.getName())) {
            return ResultUtil.paramError(result, "请填写商品名称");
        }


        if (StringUtils.isEmpty(itemDTO.getThumbnail())) {
            return ResultUtil.paramError(result, "请上传商品缩略图");
        }


        if (itemDTO.getKind() == ItemKindEnum.point.getValue()) {
            //如果是积分商品
            if (itemDTO.getRefItemId() == null) {
                return ResultUtil.paramError(result, "请选择商品");
            }

        }

        return result;
    }


    @RequestMapping("/point/insert")
    @ResponseBody
    public Result insertPoint(@RequestBody ItemDTO itemDTO) {
        Result result = new Result();
        itemDTO.setKind(ItemKindEnum.point.getValue());

        //校验
        Result validateResult = validation(itemDTO);

        if (!ResultUtil.isSuccess(validateResult)) {
            //校验失败
            return validateResult;
        }

        User currentUser = userService.getCurrentUser();
        itemDTO.setOrgId(currentUser.getOrgId());
        result = portalItemService.insert(itemDTO, currentUser.getId());

        return result;
    }


    @RequestMapping("/vip/insert")
    @ResponseBody
    public Result insertVip(@RequestBody ItemDTO itemDTO) {
        Result result = new Result();

        itemDTO.setKind(ItemKindEnum.vip.getValue());

        //校验
        Result validateResult = validationVip(itemDTO);

        if (!ResultUtil.isSuccess(validateResult)) {
            //校验失败
            return validateResult;
        }

        User currentUser = userService.getCurrentUser();

//        itemDTO.setExpiry(itemDTO.getExpiryType() + ":" + itemDTO.getExpiryValue());

        itemDTO.setOrgId(currentUser.getOrgId());
        result = portalItemService.insert(itemDTO, currentUser.getId());

        return result;
    }

    private Result validationVip(ItemDTO itemDTO) {
        Result result = new Result();

        if (StringUtils.isEmpty(itemDTO.getName())) {
            return ResultUtil.paramError(result, "请填写商品名称");
        }

//        if (itemDTO.getExpiryType() == null) {
//            return ResultUtil.paramError(result, "请选择有效期类型");
//        }

//        if (StringUtils.isEmpty(itemDTO.getExpiryValue())) {
//            return ResultUtil.paramError(result, "请填写有效期");
//        }

        if (itemDTO.getPayType() == null) {
            return ResultUtil.paramError(result, "请选择支付类型");
        }

        boolean pointFlag = ItemPayType.POINT.getValue() == itemDTO.getPayType() && itemDTO.getPointPrice() == null;

        if (pointFlag) {
            return ResultUtil.paramError(result, "请填写积分");
        }

        boolean priceFlag = ItemPayType.CASH.getValue() == itemDTO.getPayType() && itemDTO.getSalePrice() == null;

        if (priceFlag) {
            return ResultUtil.paramError(result, "请填写金额");
        }

/*
        if (StringUtils.isEmpty(itemDTO.getThumbnail())) {
            return ResultUtil.paramError(result, "请上传缩略图");
        }*/
        return result;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Result update(@RequestBody ItemDTO itemDTO) {

        Result result = new Result();

        Integer itemId = itemDTO.getId();
        if (itemId == null) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            result.setErrMsg("参数错误");
            return result;
        }

        ItemStatusEnum status = portalItemService.getStatusByItemId(itemId);

        if (!ItemStatusEnum.canEdit(status)) {
            return ResultUtil.paramError(result, "该商品不可以编辑");
        }

        //校验
        Result validateResult = validation(itemDTO);

        if (!ResultUtil.isSuccess(validateResult)) {
            //校验失败
            return validateResult;
        }


        result = portalItemService.update(itemDTO, userService.getCurrentUserId());

        return result;
    }


    @RequestMapping("/delete")
    @ResponseBody
    public Result delete(@RequestBody ItemDTO itemDTO) {
        Result result = new Result();

        if (itemDTO.getId() == null) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            result.setErrMsg("参数错误");
            return result;
        }
        result = portalItemService.delete(itemDTO);

        return result;
    }

/*    @RequestMapping("/detail")
    @ResponseBody
    public Result detail(@RequestBody ItemCriteria itemCriteria) {
        Result result = new Result();

        if (itemCriteria.getItemId() == null) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            result.setErrMsg("参数错误");
            return result;
        }
        result = portalItemService.detail(itemCriteria);

        return result;
    }*/

    @RequestMapping("/detail")
    public ModelAndView detail(@RequestParam("itemId") Integer itemId, @RequestParam("kind") Integer kind) {
        ModelAndView mv;
        if (kind != 3) { // 非积分商品
            mv = new ModelAndView("item/detail");
        } else { // 积分商品
            mv = new ModelAndView("item/addPoints");
        }

        ItemCriteria criteria = new ItemCriteria();
        criteria.setItemId(itemId);

        mv.addObject("detail", JsonUtil.toJSON(portalItemService.detail(criteria).getData().get("detail")));
        mv.addObject("readonly", "true");
        this.getUserData(mv);

        return mv;
    }


    @RequestMapping("/submit")
    @ResponseBody
    public Result submit(@RequestBody ItemDTO itemDTO) {
        Result result = new Result();

        if (itemDTO.getId() == null) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            result.setErrMsg("参数错误");
            return result;
        }
        result = portalItemService.submit(itemDTO, userService.getCurrentUserId());

        return result;
    }


    @RequestMapping("/online")
    @ResponseBody
    public Result onLine(@RequestBody ItemDTO itemDTO) {
        Result result = new Result();

        if (itemDTO.getId() == null) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            result.setErrMsg("参数错误");
            return result;
        }
        result = portalItemService.onLine(itemDTO, userService.getCurrentUserId());

        return result;
    }


    @RequestMapping("/offline")
    @ResponseBody
    public Result offLine(@RequestBody ItemDTO itemDTO) {
        Result result = new Result();

        if (itemDTO.getId() == null) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            result.setErrMsg("参数错误");
            return result;
        }

        result = portalItemService.offLine(itemDTO, userService.getCurrentUserId());

        return result;
    }

    @RequestMapping("/check")
    @ResponseBody
    public Result check(@RequestBody ItemCheck itemCheck) {
        Result result = new Result();

        if (itemCheck.getContentId() == null) {
            result.setStatus(ResultStatusEnum.参数错误.getCode());
            result.setErrMsg("参数错误");
            return result;
        }


        result = portalItemService.checkItem(itemCheck, userService.getCurrentUserId());

        return result;
    }

    @RequestMapping("/check/list")
    @ResponseBody
    public Result checkList(@RequestBody ItemCheckCriteria itemCheckCriteria) {
        Result result = new Result();

        result = portalItemService.checkList(itemCheckCriteria);

        return result;
    }


    @RequestMapping("/listByItemId")
    @ResponseBody
    public Result listByItemId(@RequestBody ItemCriteria itemCriteria) {
        Result result = new Result();
        if (CollectionUtils.isEmpty(itemCriteria.getIds())) {

            return ResultUtil.paramError(result, "参数错误");
        }

        User user = userService.getCurrentUser();
        if (UserType.seller.getValue() == user.getType()) {
            itemCriteria.setOrgId(user.getOrgId());
        }
        result = portalItemService.pageList(itemCriteria);

        return result;
    }

}
